<template>
  <div
    ref="input"
    class="edit-div"
    contenteditable="plaintext-only"
    v-text="text"
    @input="changeText"
    @focus="isfocus = true"
    @blur="isfocus = false"
    :placeholder="placeholderStr"
  ></div>
  <!-- <div>{{ text }}</div> -->
</template>
<script>
export default {
  props: ["modelValue", "placeholder", "maxlength"],
  data() {
    return {
      text: this.modelValue,
      isfocus: false
    };
  },
  watch: {
    modelValue: {
      handler(fresh, old) {
        if (!this.isfocus || !this.text) {
          this.text = fresh;
        }
      },
      immediate: true
    }
  },
  computed: {
    placeholderStr() {
      // console.log("33");
      let text = this.text;
      let showPlaceholder = !text && this.placeholder;
      // console.log("33", showPlaceholder);
      return showPlaceholder ? this.placeholder : "";
    }
  },
  methods: {
    changeText(ev) {
      let text = ev.target.innerText;
      let maxlength = this.maxlength;
      // if (text.length > maxlength) {
      //   //实现input maxlength功能
      //   text = text.substr(0, maxlength);
      //   var sel = window.getSelection();
      //   let start = sel.anchorOffset;
      //   start = Math.min(maxlength, start);
      //   ev.target.innerText = text;
      //   this.$nextTick(() => {
      //     // console.log(sel.addRange, start, sel);
      //     var el = ev.target;
      //     var range = document.createRange();
      //     range.setStart(el.firstChild, start);
      //     // range.setEnd(el.firstChild, start);
      //     // range.selectNodeContents(el);
      //     range.collapse(false);
      //     sel.removeAllRanges();
      //     sel.addRange(range);

      //     //input 控制鼠标光标
      //     // var input = document.getElementById("input");
      //     // input.setSelectionRange(input.selectionStart, input.selectionStart); //
      //   });
      // }
      if (!text) {
        this.text = text;
      }
      this.$emit("update:modelValue", text);
    }
  }
};
</script>
<style>
.edit-div {
  max-width: 100%;
  outline: none;
  cursor: text;
  white-space: pre-wrap;
  overflow-wrap: break-word;
  letter-spacing: 0.04em;
  padding: 5px;
  user-select: text;
}
.edit-div::before {
  content: attr(placeholder);
  /* opacity: 0.6; */
  color: var(--color-gray);
  font-size: 0.9rem;
}
</style>
